package com.lge.qcontact;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class ImageMovingView extends SurfaceView implements SurfaceHolder.Callback,Runnable
{

	private SurfaceHolder holder;
	private Bitmap bitmap;
	
	private Bitmap iQ; 
	private Thread thread;
	private boolean runThread = true;
	
	public boolean isRunThread() {
		return runThread;
	}

	public void setRunThread(boolean runThread) {
		this.runThread = runThread;
	}

	public ImageMovingView(Context context) {
		super(context);
		
		// TODO Auto-generated constructor stub
		holder = getHolder();
		holder.addCallback(this);
		holder.setFixedSize(getWidth(), getHeight());
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Canvas canvas;
		int py = -iQ.getHeight();
		int vy = 10;
		int jump = (getHeight()-iQ.getHeight()-20)/2;
		boolean updown = false;
		int jumpcnt =0;
		//
		while(runThread)
		{
			if(jumpcnt<=3)
			{
				if(updown==false)
				{
					if(py<getHeight()-iQ.getHeight()-20)
					{
						py+=vy;
						vy++;
					}
					else
					{
						updown = true;
					}
				}
				else 
				{
					if(vy>=0)
					{
						py-=vy;
						vy-=3;
					}
					else
					{
						jump+=jump/2;
						updown = false;
						jumpcnt++;
					}
				}
			}else
			{
				runThread = false;
			}
			canvas = holder.lockCanvas();
			canvas.drawColor(Color.WHITE);
			canvas.drawBitmap(iQ, getWidth()/2-iQ.getWidth()/2,py, null);
			holder.unlockCanvasAndPost(canvas);



			try {
				Thread.sleep(5);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_q);
		
		iQ = Bitmap.createScaledBitmap(bitmap, getWidth()/4, getHeight()/4, true);
		//
		thread = new Thread(this);
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		 
		 try {
			 runThread = false;
			 thread.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}